package com.cnebula.uas.sso.service.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import com.cnebula.uas.sso.ConfAdmin;
import com.cnebula.uas.sso.service.TenantManService;
import com.cnebula.uas.sso.util.Constant;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

@Service
public class TenantManServiceImpl implements TenantManService {

	Logger log = LoggerFactory.getLogger(TenantManServiceImpl.class);

	CloseableHttpClient httpClient = HttpClients.createDefault();

	@Autowired
	ConfAdmin conf;

	String okapiTenantsURL;

	ObjectMapper mapper = new ObjectMapper();

	@PostConstruct
	public void init() {

		StringBuilder okapiTenantsURLBuilder = new StringBuilder();
		okapiTenantsURLBuilder.append("http://").append("222.29.81.251").append(":").append(9130);
		okapiTenantsURLBuilder.append("/tenantman/pub/tenants");

		okapiTenantsURL = okapiTenantsURLBuilder.toString();
	}

	@Override
	public ResponseEntity<String> getCalisCode(String id) {

		return null;
	}

	@Override
	public ResponseEntity<String> getTenantId(String calisCode) throws Exception {

		CloseableHttpResponse res = null;
		List<Map<String, String>> list = null;
		try {
			URIBuilder builder = new URIBuilder(okapiTenantsURL);
			builder.setParameter("query", "[[\"tenant.tenant_ins.code_calis\",\"" + calisCode + "\",\"=\",\"AND\"]]");
			HttpGet httpGet = new HttpGet(builder.build());

			httpGet.addHeader(Constant.OKAPI_TENANT_HEADER, conf.supertenant);

			res = httpClient.execute(httpGet);
			HttpEntity entity = res.getEntity();
			String content = EntityUtils.toString(entity);
			int statusCode = res.getStatusLine().getStatusCode();
			EntityUtils.consume(entity);
			if (statusCode != 200) {
				return ResponseEntity.status(statusCode).body(content);
			}
			list = mapper.readValue(content, new TypeReference<List<Map<String, String>>>() {
			});

		} finally {
			if (res != null) {
				res.close();
			}

		}

		if (list == null || list.isEmpty()) {
			return ResponseEntity.badRequest().build();
		}

		String tenantId = list.get(0).get("id");

		return ResponseEntity.ok(tenantId);

	}

}
